from PIL import Image

img = Image.open('1.png')

img_gray = img.convert('L')

#进行二值化,求平均像素
def binary(im):
    x, y = im.size  #417 ,211
    print(x,y)
    sum = 0
    for i in range(x):
        for j in range(y):
            img = im.getpixel((i, j))
            print(img)
            sum += img

    for i in range(x):
        for j in range(y):
            p = im.getpixel((i, j))
            if p > sum/x/y:
                im.putpixel((i, j), 255)
            else:
                im.putpixel((i, j), 0)
    return im

#降噪
def point(x, y, fanwei):

    for i in range(x-fanwei,x+fanwei):
        for j in range(y-fanwei,y+fanwei):
            if i == x and j == y:
                continue
            else:
                yield (i,j)

#整体实现
def save_img(im):
    x, y = im.size
    fanwei = 5
    for i in range(x):
        for j in range(y):
            p = im.getpixel((i, j))
            print(p)
            if p < 100:
                count = 0
                for m, n in point(i, j, fanwei):
                    if im.getpixel((m, n)) > 100:
                        count += 1
                if count > 0.5*((fanwei*2+1)**2-1):
                    im.putpixel((i, j), 255)
    return im



img_save = binary(img_gray)
img_save.save('img.save.png')
img1 = save_img(img_save)
img1.save('img1.png')